package com.comment.utils;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.comment.dto.UserDTO;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class RefreshTokenInterceptor implements HandlerInterceptor {

    private StringRedisTemplate redisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.获取请求头中的token
        String token = request.getHeader("authorization");
        if (StrUtil.isEmpty(token)){
            // 2.如果token为空，直接放行
            return true;
        }
        // 2.获取token中的User对象
        Map<Object, Object> userMap = redisTemplate.opsForHash().entries("login:token:" + token);
        // 3.判断用户是否存在
        if (userMap.isEmpty()) {
            // 4.如果用户不存在，直接放行
            return true;
        }
        // 5.将查询到的Hash数据转为UserDTO对象
        UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);
        // 6.如果用户存在，保存用户信息到ThreadLocal中
        UserHolder.saveUser(userDTO);
        // 7.刷新token的有效期
        redisTemplate.expire("login:token:" + token,30, TimeUnit.MINUTES);
        // 8.放行请求
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 7.请求处理完成后，清除ThreadLocal中的用户信息
        UserHolder.removeUser();
    }
}
